<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElButton } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'
import request from '@/utils/request.js'

export default {
  name: 'ChangeAvatar',
  components: {
    ElButton
  },
  setup() {
    const userInfo = ref({})
    const tokenStore = useTokenStore()
    const fileInput = ref(null)
    const newAvatar = ref('')

    const getUserInfo = async () => {
      try {
        const response = await request.get('/user/info')
        if (response.code === 1) {
          userInfo.value = response.data
        } else {
          ElMessage.error(response.msg || '获取用户信息失败')
        }
      } catch (error) {
        ElMessage.error('服务异常')
      }
    }

    const handleChangeFile = async (event) => {
      const file = event.target.files[0]
      if (!file) return

      const formData = new FormData()
      formData.append('file', file)

      try {
        const uploadResponse = await request.post('/upload', formData)

        if (uploadResponse.code === 1) {
          const updateResponse = await updateUserAvatar(uploadResponse.data)
          if (updateResponse.code === 1) {
            userInfo.value.avatar = uploadResponse.data
            newAvatar.value = uploadResponse.data
            ElMessage.success('头像更新成功')
          } else {
            ElMessage.error(updateResponse.msg || '更新头像失败')
          }
        } else {
          ElMessage.error(uploadResponse.msg || '上传头像失败')
        }
      } catch (error) {
        console.error(error)
        ElMessage.error('服务异常')
      }
    }

    const handleClick = () => {
      fileInput.value.click()
    }

    const updateUserAvatar = async (newAvatar) => {
      try {
        const response = await request.put('/user', {
          id: userInfo.value.id,
          avatar: newAvatar
        })

        return response
      } catch (error) {
        console.error(error)
        return { code: -1, msg: '服务异常' }
      }
    }

    onMounted(() => {
      getUserInfo()
    })

    return {
      userInfo,
      fileInput,
      handleClick,
      handleChangeFile
    }
  }
}
</script>

<template>
  <div class="change-avatar">
    <div class="demo-image__preview">
      <el-image
        style="width: 300px; height: 300px"
        :src="userInfo.avatar"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        :preview-src-list="[userInfo.avatar]"
        fit="cover"
      />
    </div>
    <input type="file" ref="fileInput" @change="handleChangeFile" accept="image/*" style="display:none" />
    <el-button @click="handleClick">更改头像</el-button>
  </div>
</template>

<style scoped>
.change-avatar .demo-image__preview {
  width: 300px;
  height: 300px;
  overflow: hidden;
}

.change-avatar .el-button {
  margin-top: 0px;
  margin-left: -1400px;
}
</style>